package org.spotem.api;

import org.spotem.model.TrackPoint;
import org.spotem.model.TrackPointImpl;
import org.spotem.service.TrackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.LinkedList;
import java.util.List;

@Path("/api/track")
@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_JSON)
@Component
public class TrackController extends ApiController {

    @Autowired
    private TrackService trackService;

    @GET
    @Path("/find")
    public Object findTrack(@Context HttpServletRequest request) {
        String trackKey = request.getParameter("trackKey");
        if(trackKey != null) {
            return trackService.findTrack(trackKey);
        }
        return null;
    }

    @GET
    @Path("/points/find")
    public List<? extends TrackPoint> findTrackPoints(@Context HttpServletRequest request) {
        String trackKey = request.getParameter("trackKey");
        if(trackKey != null) {
            String lastPointId = request.getParameter("lastPointId");
            Long minId = 0L;
            if(lastPointId != null) {
                try {
                    minId = Long.valueOf(lastPointId);
                } catch (Throwable th) {
                }
            }
            List<TrackPointImpl> points = trackService.findTrackPoints(trackKey, minId);
            return points;
        }
        return new LinkedList<>();
    }

    @GET
    @Path("/ack/{trackKey}")
    public String ack(@Context final HttpServletRequest request, @PathParam("trackKey") String trackKey) {
        String[] latParams = {"lat", "latitude"};
        String[] lonParams = {"lon", "lng", "longitude"};
        String[] altParams = {"alt", "altitude"};
        String slat = null;
        for(int i = 0; i < latParams.length && slat == null; i++) {
            slat = request.getParameter(latParams[i]);
        }
        String slon = null;
        for(int i = 0; i < lonParams.length && slon == null; i++) {
            slon = request.getParameter(lonParams[i]);
        }
        String salt = null;
        for(int i = 0; i < altParams.length && salt == null; i++) {
            salt = request.getParameter(altParams[i]);
        }
        if(slat != null && slon != null) {
            double lat = Double.valueOf(slat);
            double lon = Double.valueOf(slon);
            logger.info(trackKey + ": " + lat + ", " + lon);
            trackService.addTrackPoint(trackKey, lat, lon);
        }
        return "";
    }
}
